package com.etooling.pdm.repository;

import com.etooling.framework.repository.BaseRepository;
import com.etooling.pdm.entity.BomDetail;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public interface BomDetailRepository extends BaseRepository<BomDetail> {


    @Transactional
    @Modifying
    @Query(value = "delete from pdm.t_bom_detail where bom_id =?1 ", nativeQuery = true)
    void deleteByBomId(String bomId);


    /**
     * 删除BomDetail以及它的所有子级
     *
     * @param bomDetailId
     */
    @Transactional
    @Modifying
    @Query(value = "WITH RECURSIVE descendants_to_delete AS (" +
            "    SELECT id " +
            "    FROM pdm.t_bom_detail " +
            "    WHERE id = ?1 OR parent_id = ?1 " +  // 确保包含自身ID
            "    UNION ALL " +
            "    SELECT t.id " +
            "    FROM pdm.t_bom_detail t " +
            "    JOIN descendants_to_delete d ON t.parent_id = d.id " +
            ") " +
            "DELETE FROM pdm.t_bom_detail " +
            "WHERE id IN (SELECT id FROM descendants_to_delete)",
            nativeQuery = true)
    void delBomDetail(String bomDetailId);


    @Query(nativeQuery = true, value = "select * from pdm.t_bom_detail as b where bom_id =?1 ")
    List<BomDetail> getByBomId(String id);


    /**
     * 根绝bomDetail 的父类id, 找出这个父类id下最大的seq是多少
     *
     * @param parentBomDetailId
     * @return
     */
    @Query(nativeQuery = true, value = "select seq from pdm.t_bom_detail where parent_id = ?1 order by seq desc limit 1")
    Integer getMaxSeq(String parentBomDetailId);


}
